#include <workflow/WFHttpServer.h>
#include <workflow/WFFacilities.h>
#include <workflow/HttpMessage.h>

#include <string>
#include <iostream>
#include <signal.h>
#include <time.h>

#include "CryptoUtil.h"
#include "User.h"

using namespace std;
using namespace protocol;

void doLogin(WFHttpTask *task);
void doRegister(WFHttpTask *task);
void doDownLoad(WFHttpTask *task);

void process(WFHttpTask *task){
    
    HttpRequest *req = task->get_req();
    string method = req->get_method();
    string uri = req->get_request_uri();
    if(method == "POST" && uri == "/login"){
        doLogin(task);
    }else if(method == "POST" && uri == "/register"){
        doRegister(task);
    }else if(method == "GET" && uri == "/"){
        doDownLoad(task);
    }
}

void doLogin(WFHttpTask *task){

}

void doRegister(WFHttpTask *task){
    cout<<"doRegister"<<endl;
    HttpRequest *req = task->get_req();
    const void *body;
    size_t body_size;
    req->get_parsed_body(&body,&body_size);
    string body_str((char *)body,body_size);
    cout<<"body_str:"<<body_str<<endl;
    auto pos = body_str.find("&");
    string username = body_str.substr(0,pos);
    string password = body_str.substr(pos+1);
    cout<<"username:"<<username<<endl;
    cout<<"password:"<<password<<endl;
    SeriesWork *series = series_of(task);
    string salt = CryptoUtil::generate_salt(10);
    string hash_password = CryptoUtil::hash_password(password,salt);
    cout<<"salt:"<<salt<<endl;
    cout<<"hash_password:"<<hash_password<<endl;
}

void doDownLoad(WFHttpTask *task){}

WFFacilities::WaitGroup g_waitGroup{1};

void sig_handler(int signo){
    g_waitGroup.done();
}

int main(int argc,char *argv[]){
    signal(SIGINT,sig_handler);

    WFHttpServer server{process};
    if(server.start(12345)==0){
        g_waitGroup.wait();
        server.stop();
    }else{
        cerr<<"start server falied"<<endl;
        return 0;
    }
}